/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.managers;

import com.alee.managers.settings.SettingsManager;
import com.alee.utils.collection.ValuesTable;
import com.rag.core.User;

/**
 * User: mgarin Date: 07.06.12 Time: 17:30
 */

public class UsersManager
{
    private static String usersFile = "Users.xml";

    private static boolean initialized = false;

    private static final Object usersLock = new Object ();
    private static ValuesTable<String, User> users = null;

    public static void initializeManager ()
    {
        if ( !initialized )
        {
            initialized = true;

            // Загружаем список закэшированных пользователей
            loadUsers ();
        }
    }

    /**
     * Получаем пользователя по ID
     */

    public static User getUser ( String userId )
    {
        synchronized ( usersLock )
        {
            return users.get ( userId );
        }
    }

    /**
     * Кэшируем данные о пользователе
     */

    public static void cacheUser ( User user )
    {
        synchronized ( usersLock )
        {
            users.put ( user.getId (), user );
            saveUsers ();
        }
    }

    /**
     * Загружаем закэшированных пользователей
     */

    private static void loadUsers ()
    {
        if ( users == null )
        {
            users = SettingsManager.getSettings ( usersFile, new ValuesTable<String, User> () );
        }
    }

    /**
     * Сохраняем закэшированных пользователей
     */

    private static void saveUsers ()
    {
        SettingsManager.setSettings ( usersFile, users );
    }
}